// Copyright (C) 2019-2020 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

// dbgen -i <inputfile> -o <outputfile> -p <pkgname> -n <funcname> generates an installation function
// for a sqlite3 database schema installation.
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"strings"
	"time"
)

var inputfilename = flag.String("i", "", "Name of the file specifying the database schema.")
var outputfilename = flag.String("o", "", "Name of the file to write out the resulting output. Default is stdout.")
var fnname = flag.String("n", "", "Name of the desired installation function; signature is \"func <name>InstallDatabase(*sql.Tx) error\"")
var pkgname = flag.String("p", "", "Name of the package to place installation function in")
var headerfilename = flag.String("h", "", "Name of the header file to use")

var template = `%s// generated by dbgen; DO NOT EDIT

package %s

import "database/sql"

func ` + "%s" + `InstallDatabase(tx *sql.Tx) error {
	statement := ` + "`%s`" + `
	_, err := tx.Exec(statement)
	if err != nil {
		return err
	}

	return nil
}
`

func main() {
	flag.Parse()

	if *pkgname == "" {
		panic("error: No package name specified")
	}

	if *inputfilename == "" {
		panic("error: No database schema file specified")
	}
	input, err := ioutil.ReadFile(*inputfilename)
	if err != nil {
		panic(err)
	}
	header := ""
	if *headerfilename != "" {
		headerBytes, err := ioutil.ReadFile(*headerfilename)
		if err != nil {
			panic(err)
		}
		header = string(headerBytes) + "\n"
		header = strings.Replace(header, "{DATE_Y}", fmt.Sprintf("%d", time.Now().Year()), 1)
	}

	payload := fmt.Sprintf(template, header, *pkgname, *fnname, string(input))

	if *outputfilename == "" {
		fmt.Println(payload)
	} else {
		err := ioutil.WriteFile(*outputfilename, []byte(payload), 0666)
		if err != nil {
			panic(err)
		}
	}
}
